//
//  HYLOauthViewController.swift
//  iOSwechat
//
//  Created by apple on 16/2/27.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class HYLOauthViewController: UIViewController {

    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "新浪微博"
        // 设置背景颜色
//        view.backgroundColor = UIColor.redColor()
        
        // 加载授权登录界面
        let request = NSURLRequest(URL: HYLNetworkTool.sharedInstance.oauthLoginUrl())
        webView.loadRequest(request)

     
        setupNavigationBar()
    }
    
    
    // MARK: - 懒加载
    lazy var webView: UIWebView = UIWebView()
    
    
    // MARK: - 设置导航控制器
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // 填充
    func autoFill() {
        
        let js = "document.getElementById('userId').value='15915965549';document.getElementById('passwd').value='huangyouli1219 '"
        webView.stringByEvaluatingJavaScriptFromString(js)

    }
    
    // 关闭
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
}

extension HYLOauthViewController: UIWebViewDelegate {
    // SVProgressHUD.showWithStatus 只要不关闭，就一直显示
    // SVProgressHUD.showSuccessWithStatus 过2秒关闭
    //webView 开始加载请求
//    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.showWithStatus("正在加载登录...", maskType: SVProgressHUDMaskType.Black)
//    }
//    
//    // 加载成功
//    func webViewDidFinishLoad(webView: UIWebView) {
//        // 关闭指示器
//        SVProgressHUD.dismiss()
//        
//    }
//    
//    // 加载失败
//    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        SVProgressHUD.showErrorWithStatus("加载失败...", maskType: SVProgressHUDMaskType.Clear)
//    }
    
    // webView询问我们是否要去加载某个请求: true去加载,false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
//        print("++++++++\(urlString)")
        
        /*
        取消
        ++++++++Optional("http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")
        
        授权
        ++++++++Optional("http://www.baidu.com/?code=dcc43eb9ff84fd6643c7140da5b2300d")
        */
        
        // 1.判断是否是回调地址开头.是回调地址开头,表示用点击的是授权或取消按钮
        if urlString!.hasPrefix(HYLNetworkTool.sharedInstance.redirect_uri){
            // 需要判断是否点击取消还是授权
            // 判断？后面的是crror---取消 还是 code---授权
            let query = request.URL?.query
            //print("----------\(query)")    //code=20d1abf0bcd8c12aa04acc87aaa1cb2a
            let code = "code="
            if query!.hasPrefix(code) {
                //print("----------\(query)")
                let queryNS = query! as NSString
                // 2.授权按钮，截取code的值
                let codeString = queryNS.substringFromIndex(code.characters.count)
                print("----------\(codeString)")   //8ef59ae21f9573fe9d2a5285b0781f50
                
                // 如果将和模型相关的事情放到控制器中，控制器关心 事太多，控制器代码臃肿，创建一个类出来模型相关的MVVM
                
                //  加载accessToken 调用loadAccessToken方法加载请求  【8ef59ae21f9573fe9d2a5285b0781f50】
                // 点击填充 登录微博
                HYLUserAccountViewModel.sharedInstance.loadAccessToken(codeString, loadAccessTokenCallBack: { (error) -> () in
                    if error != nil {
                        print("获取accessToken出错了: \(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力...")
                        // 关闭控制器
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { ()-> Void in
                            self.close()
                        })
                        return
                    }
                    // 切换到欢迎界面
                  //(UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(false)
                    // 类方法调用，方便别的程序员调用
                    AppDelegate.outswitchViewController(false)
                    // 保存账号成功
                    self.close()
                })
            } else {
                // 取消按钮,关闭控制器
                close()
            }
            return false
        }
        // 2.不是授权回调地址,直接加载这个请求
        return true
    }
    
}



